//
//  AccountCenterController.m
//  tuanGG
//
//  Created by 李洪旭 on 15/9/21.
//  Copyright (c) 2015年 weita. All rights reserved.
//

#import "AccountCenterController.h"
#import "Header.h"
#import "AccountCenterViewCell.h"
#import "PotoBaseControl.h"
#import "MyAccountController.h"
#import "MyDataViewController.h"
#import "HomeViewController.h"
#import "LoginViewController.h"
#import "Common.h"
#import "InviteCodeViewController.h"
#import "SettingMoreControl.h"
#import "AboutViewController.h"
#import "MessageViewController.h"
@interface AccountCenterController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,WJPhotoTool>
@property (strong,nonatomic)NSArray *array;
@property (nonatomic,strong)NSArray *imageArray;
@property (nonatomic,strong)UIImageView *imageView;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIImageView *headView;
@property (nonatomic,strong)UILabel *nameLabel;
@property (nonatomic,strong)UILabel *accountLabel;
@property (nonatomic,strong)UILabel *price;
@property (nonatomic,strong)UIButton *shadowView;
@property (nonatomic,strong)UIButton *loginButton;
@property (nonatomic,strong)UIImageView *userImage;
@property (nonatomic,strong)UIButton *userButton;
@end

@implementation AccountCenterController
- (void)viewWillAppear:(BOOL)animated {
    [self tabBarHidden];
    if ([UserInfo sharedUserInfo].loginStatus == NO) {

    }
}
- (id)init{
    self= [super init];
    if (self) {
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:IMGNAME(@"消息") style:UIBarButtonItemStylePlain target:self action:@selector(message)];

        self.navigationItem.rightBarButtonItem = rightItem;

    }
    return  self;
}
- (void)message{
    MessageViewController *message = [[MessageViewController alloc]init];
    [self.navigationController pushViewController:message animated:YES];
}
- (void)navButton:(UIButton *)sender {

    if ([UserInfo sharedUserInfo].loginStatus == NO) {
        HomeViewController *home = [[HomeViewController alloc]init];
        [self.navigationController presentViewController:home animated:YES completion:nil];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self addnavigationTitle:@"商家中心" navColor:@"4fd2be"];
    [self initView];
    [self addTableView];
    NSLog(@"登录状态:%zi",[UserInfo sharedUserInfo].loginStatus);
    
}
- (void)initView {
    _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight/4)];
    [_imageView sd_setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"about_ zhuye"]];
    [self.view addSubview:_imageView];
    
    _headView = [[UIImageView alloc]initWithFrame:CGRectMake(_imageView.frame.size.height/4, _imageView.frame.size.height/4, _imageView.frame.size.height/2, _imageView.frame.size.height/2)];
    _headView.layer.cornerRadius = _imageView.frame.size.height/4;
    _headView.layer.masksToBounds = YES;
    if (![[User_member instance].avatarm isEqualToString:@""]) {
        [_headView sd_setImageWithURL:[NSURL URLWithString:[User_member instance].avatarm]];
    }else{
        [_headView sd_setImageWithURL:nil placeholderImage:IMGNAME(@"BsLoginHead")];
    }
    _userButton = [[UIButton alloc]initWithFrame:CGRectMake(_imageView.frame.size.height/4, _imageView.frame.size.height/4, _imageView.frame.size.height/2, _imageView.frame.size.height/2)];
    _userButton.tag = 100;
    _userButton.backgroundColor = [UIColor clearColor];
    [_userButton addTarget:self action:@selector(headButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_headView];
    [self.view addSubview:_userButton];
    
    _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(_imageView.frame.size.height/4*3+10, _imageView.frame.size.height/2-30, _imageView.frame.size.width-_imageView.frame.size.height/4*3-_imageView.frame.size.height/4,20)];
    _nameLabel.text = [User_member instance].username;
    _nameLabel.textAlignment = NSTextAlignmentLeft;
    _nameLabel.font = [UIFont fontWithName:font_Font size:15];
    _nameLabel.textColor = [UIColor whiteColor];
    [_imageView addSubview:_nameLabel];
    _accountLabel =  [[UILabel alloc]initWithFrame:CGRectMake(_imageView.frame.size.height/4*3+10,_imageView.frame.size.height/2+10 , 75, 20)];
    _accountLabel.text = @"账户余额：";
    _accountLabel.font = [UIFont fontWithName:font_Font size:15];
    _accountLabel.textColor = [UIColor whiteColor];
    [_imageView addSubview:_accountLabel];
    
    _price = [[UILabel alloc]initWithFrame:CGRectMake(_accountLabel.frame.origin.x+_accountLabel.frame.size.width, _imageView.frame.size.height/2+10, ScreenWidth/2, 20)];
    _price.textColor = [UIColor whiteColor];
    _price.font = [UIFont fontWithName:font_Font size:14];
    NSLog(@"%@",[User_member instance].balance);
    _price.text = [NSString stringWithFormat:@"%@元",[User_member instance].balance];
    [_imageView addSubview:_price];


//    [self.view insertSubview:_shadowView atIndex:5];
}

- (void)addTableView {
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, _imageView.frame.size.height, ScreenWidth, ScreenHeight-_imageView.frame.size.height) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource =self;
    _tableView.bounces = NO;
    [_tableView registerClass:[AccountCenterViewCell class] forCellReuseIdentifier:@"CELL"];
    [self.view addSubview:_tableView];
    UIButton *exitButton = [[UIButton alloc]initWithFrame:CGRectMake(10, _tableView.frame.size.height-10, ScreenWidth-20, 50)];
    [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitButton setBackgroundImage:[UIImage imageNamed:@"BsLoginOutBtn"] forState:UIControlStateNormal];
    [exitButton addTarget:self action:@selector(exitButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exitButton];

    _shadowView = [[UIButton alloc]initWithFrame:CGRectMake(0, _imageView.frame.size.height, ScreenWidth, ScreenHeight-_imageView.frame.size.height)];
    _shadowView.hidden = YES;
    _shadowView.backgroundColor = [UIColor blackColor];
    _shadowView.alpha = 0.3;
//    _shadowView.tag = 102;
    [_shadowView addTarget:self action:@selector(headButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_shadowView];

    _loginButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 20)];
    _loginButton.center = CGPointMake(ScreenWidth/2, _imageView.frame.size.height/2+40);
    _loginButton.backgroundColor = [UIColor whiteColor];
    _loginButton.layer.cornerRadius = 5;
    _loginButton.hidden = YES;
    _loginButton.tag = 101;
    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [_loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_loginButton addTarget:self action:@selector(headButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginButton];
}
#pragma mark - 事件实现

- (void)headButton:(UIButton *)sender {
    if (sender.tag == 101) {
        
        NSLog(@"登录");
        HomeViewController *login = [[HomeViewController alloc]init];
        [self presentViewController:login animated:YES completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginout" object:nil];

    }else if(sender.tag == 100 ){
    NSLog(@"点击头像");
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:@"拍照"
                                                    otherButtonTitles:@"相册", nil];
    [choiceSheet showInView:self.view];
    }else if (sender.tag == 102){
        [UIView animateWithDuration:1 animations:^{
            _shadowView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight - _imageView.frame.size.height) ;
        }];
    }
}

- (void)exitButton{
    NSLog(@"退出登录");
    [self addAlert:@"您确认要退出登录" otherButtonTitles:@"取消"];

//    [self dismissViewControllerAnimated:YES completion:nil];
//    [self presentViewController:home animated:YES completion:nil];
//    [LoginViewController sharedLoginControl];
}

- (NSArray *)array {
    if (!_array) {
        _array = [[NSArray alloc]initWithObjects:@[@"我的资料",
                                                   @"我的账户"],
                  @[@"验证邀请码",@"版本更新",@"意见反馈",@"关于我们"], nil];
    }
    return _array;
}
- (NSArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [[NSArray alloc]initWithObjects:@[@"Bsdata",
                                                        @"MyAcount@2x"],
                                                       @[@"验证邀请码",
                                                         @"BsVerSion",
                                                         @"BsOpion",
                                                         @"BsAbout"], nil];
    }
    return _imageArray;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        _shadowView.hidden = NO;
        _loginButton.hidden = NO;
        _price.hidden = YES;
        _accountLabel.hidden = YES;
        _headView.hidden= YES;
        _nameLabel.frame = CGRectMake(0, 0, 120, 20);
        _nameLabel.center = CGPointMake(ScreenWidth/2, _imageView.frame.size.height/2);
        _nameLabel.textAlignment = NSTextAlignmentCenter;
        _nameLabel.text = @"赶快登陆吧！";
        [UserInfo sharedUserInfo].loginStatus = NO;
        NSLog(@"%zi",[UserInfo sharedUserInfo].loginStatus);
        [[UserInfo sharedUserInfo] saveUserInfoToSandbox];
        [[NSNotificationCenter defaultCenter] postNotificationName:HANDLETOLOGIN object:@"loginout"];

    }
}

#pragma mark - UITableViewDataSource,UITableViewDelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [(NSArray *)self.array[section]count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.array.count;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @" ";
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AccountCenterViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath ];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.name.text =_array [indexPath.section][indexPath.row] ;
    cell.image.image = [UIImage imageNamed:self.imageArray[indexPath.section][indexPath.row]];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //我的资料
    if (indexPath.row == 0 && indexPath.section == 0) {
        MyDataViewController *myVC = [[MyDataViewController alloc]init];
        myVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:myVC animated:YES];
    //我的账户
    }if (indexPath.row == 1 && indexPath.section == 0) {
        MyAccountController *myVC = [[MyAccountController alloc]init];
        myVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:myVC animated:YES];
    //验证邀请码
    }if (indexPath.row == 0 && indexPath.section == 1) {
        InviteCodeViewController *inviteCode = [[InviteCodeViewController alloc]init];
        [self.navigationController pushViewController:inviteCode animated:YES];
    //版本更新
    }if (indexPath.row == 1 && indexPath.section == 1) {
        [self NetWorking];
    //意见反馈
    }if (indexPath.row == 2 && indexPath.section == 1) {
        SettingMoreControl *setting = [[SettingMoreControl alloc]init];
        [self.navigationController pushViewController:setting animated:YES];
    //关于我们
    }if (indexPath.row == 3 && indexPath.section == 1) {
        AboutViewController *about = [[AboutViewController alloc]init];
        [self.navigationController pushViewController:about animated:YES];
    }
        
   
}


#pragma mark - <UIActionSheetDelegate>

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            WJPhotoTool *wj = [WJPhotoTool sharedWJPhotoTool];
            [wj WJUIImagePiker:self type:1 needCut:YES block:^(UIImage *edtingImage, UIImage *originalImage) {
                [self requestOfFruit:edtingImage];
            }];
        }
    }if (buttonIndex == 0) {
        WJPhotoTool *wj = [WJPhotoTool sharedWJPhotoTool];
        [wj WJUIImagePiker:self type:0 needCut:YES block:^(UIImage *edtingImage, UIImage *originalImage) {
            
        }];
        
    }
}
#pragma mark - <UIImagePickerControllerDelegate>
//用户选中了某个媒体

//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//    UIImage *editedImage = info[UIImagePickerControllerEditedImage];
//
//    [self dismissViewControllerAnimated:YES completion:^{
//
//        
//    }];
//}
/**
 *  修改头像
 */
- (void)requestOfFruit:(UIImage *)image{
    //上个界面没有传id
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    NSMutableDictionary *dicImage = [[NSMutableDictionary alloc]init];
    [dicImage setObject:image forKey:@"userimg"];
    [GLAFRequest startFileRequest:Setting_headimgae_url time:20 isTouch:YES paramsDic:dic defaultdialog:YES picDic:dicImage handleSuccess:^(id sta, NSDictionary *paramsDic) {
        NSLog(@"信息：%@",sta);
        if ([sta[@"code"]integerValue] == 1) {
            //清除图片缓存
            [[SDWebImageManager sharedManager].imageCache clearDisk];
            [Common deleteNSUserDefaults:Setting_headimgae_url];
            [_headView sd_setImageWithURL:[NSURL URLWithString:[User_member instance].avatarm]];
            [Common addAlert:@"修改头像成功"];
            [_tableView reloadData];
        }
    } netWorkFail:^(NSDictionary *paramsDic) {
        
    }];
}
- (void)NetWorking {

    NSDictionary *dictionary = @{@"versionnum":@"1.0.0"};
    [GLAFRequest startRequest:version_url paramsDic:dictionary defaultdialog:YES ispost:NO handleSuccess:^(id sta, NSDictionary *paramsDic) {
        NSLog(@"%@",sta);
        if ([sta[@"code"]integerValue] == 1) {
            if ([[NSString stringWithFormat:@"%@",sta[@"pramaters"][@"versionnum"]]isEqualToString:[NSString stringWithFormat:@"%@",sta[@"pramaters"][@"appversion"]]]) {
                [Common addAlert:@"已经是最新版本"];
            }else{
                [Common addAlert:@"有更新版本"];
            }

        }
    } doFinally:^(NSDictionary *paramsDic) {
        
    }];
}
@end
